<?php
/**
 * 第三方卡券，仅在本平台显示
 */
namespace Common\Model;
use Think\Exception;
use Think\Model;

class ThirdCouponModel extends BaseModel
{
	private static $instance=null;
	private function getInstance(){
		if(!self::$instance){
			self::$instance=M('third_coupon',null,DB_MAIN_CFG);
		}
		return self::$instance;
	}


	//卡券类型
	const COUPON_TYPE_CASH			= 1;//代金券
	const COUPON_TYPE_ITEM			= 2;//项目券

	/**
	 * 根据卡券号获取卡券信息
	 * Author: shijy
	 * @param $code
	 * @return array
	 */
	public static function getCouponInfo($code){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		if(strlen($code)<12){
			$dataFailure['msg']='卡券号长度错误！';
			return $dataFailure;
		}
		$codeInfo=M('card_code',null,DB_MAIN_CFG)->where("code='{$code}'")->find();
		if(!$codeInfo){
			$dataFailure['msg']='卡券号不存在';
			return $dataFailure;
		}

		$codeInfo['restaurantName']='';
		if($codeInfo['restaurantId']!=0){
			$restaurantName=M('s_restaurant',null,DB_MAIN_CFG)->where('id='.$codeInfo['restaurantId'])->getField('restaurantName');
			$codeInfo['restaurantName']=$restaurantName;
		}
		$dataSuccess['data']=$codeInfo;

		return $dataSuccess;
	}




	/**
	 * 核销卡券号
	 * Author: shijy
	 * @param $consumeFrom 核销来源
	 * @param $verificationId 核销工号
	 * @param $code 卡券号
	 * @param $verificationStoreId 核销者门店
	 * @param $verificationRestaurantId 核销者商户编号
	 * @return array
	 */
	public static function consumeCoupon($thirdId,$couponType,$couponFrom){
		//更改卡券的使用状态
		$codeUpdate=array(
			'couponStatus'=>CouponModel::CODE_STATUS_USED,
			'updateTime'=>time()
		);
		$result=self::getInstance()->where("couponFrom='{$couponFrom}' and couponType='{$couponType}' and tid='{$thirdId}'")->save($codeUpdate);
		if($result===false){
			$dataFailure = array('status'=>self::FAILURE,'msg'=>'核销失败');
			return $dataFailure;
		}
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		return $dataSuccess;
	}






	public static function getCouponList($ownerUid,$codeStutus=-1,$page=1,$pageSize=30){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$where='1';
		if($ownerUid>0){
			$where .=' and uid='.$ownerUid;
		}

		if ($codeStutus>=0){
			$where .=' and couponStatus='.$codeStutus;
		}

		if(!$page){
			$page=1;
		}
		$M=self::getInstance();
		$rowCount=$M->where($where)->count();

		$pageCount=max(1,ceil($rowCount/$pageSize));
		$page=min(max($page,1),$pageCount);
		$offset=($page-1) * $pageSize;

		$list=$M->where($where)
			->order('updateTime DESC,addTime DESC')
			->limit($offset,$pageSize)
			->select();

		///////////////////////////////////////////////////
		$dataSuccess['total']	=$rowCount;
		$dataSuccess['totalPage']=$pageCount;
		$dataSuccess['page']	=$page;
		$dataSuccess['nextPage'] = $page >= $pageCount ? 0 : 1;//是有有下一页
		$dataSuccess['list']	=$list;
		return $dataSuccess;
	}
	
}